#!/usr/bin/env python3

import asyncio
import fire
import os
import pathlib
import sys
import requests

_file = pathlib.Path(__file__)
_root = _file.parent

sys.path.append(str(_root))

from rr.api import ServerHelper


class Cli:

    def add_file(
        self,
        path: str,
        uuid: str | None = None,
        task_hash: str | None = None,
        type_: str = "file",
        content_type: str = "application/raw",
    ):
        """
        Add a file to the server.
        """
        helper = ServerHelper()
        if uuid is None:
            uuid = os.path.basename(path)
        helper.add_file(path, uuid, task_hash, type_, content_type)

    def download_file(self, file_id: str, path: str | os.PathLike):
        """
        Download a file from the server to the local filesystem.
        """
        helper = ServerHelper()
        helper.download_file(file_id, path)

    def clear_task(self, task_id: str, server_url: str | None = None):
        """
        Clear a task from the server.
        """
        helper = ServerHelper(server_url)
        helper.clear_task(task_id)

    def run(self, task_spec_file: str, server_url: str | None = None):
        """
        Run a task.
        """
        from rr.add_task_helper import submit_task

        server_helper = ServerHelper(server_url)
        submit_task(task_spec_file, server_helper)

    def serve(
        self,
        root_path: str = "/rr_server",
    ):
        """
        Start the server.
        """
        # call unicorn to run the server
        os.system(
            f"cd {_root} && uvicorn rr.server:app --reload --port 8000 --host 0.0.0.0 --root-path {root_path}"
        )

    def add_task(self, task_spec_file: str, server_url: str | None = None):
        """
        Add a task to the server.
        """
        from rr.add_task_helper import submit_task

        server_helper = ServerHelper(server_url)
        submit_task(task_spec_file, server_helper)

    def worker_manager(
        self,
        workers: int = 1,
        server_url: str | None = None,
    ):
        """
        Run a task.
        """
        from rr.workermanager import WorkerManager

        server_helper = ServerHelper(server_url)
        worker_manager = WorkerManager(server_helper, workers)
        asyncio.run(worker_manager.loop())

    def ui(self):
        """
        Start the UI.
        """
        os.system("python -m rr.ui.server")

    def prune(self):
        """
        Prune all files that are not in the db.
        """
        from rr.api import TaskManager

        tm = TaskManager()
        tm.prune()

    wm = worker_manager
    add = add_task
    u = add_file
    d = download_file
    c = clear_task


if __name__ == "__main__":
    fire.Fire(Cli)
